package com.starbaba.messageManager.view;

import java.io.IOException;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.messageManager.model.PullBackMessageModel;
import com.starbaba.messageManager.service.PullBackMessageService;

@SuppressWarnings({"rawtypes", "unchecked", "serial"})
public class PullBackMessageAction extends BaseAction implements ModelDriven<PullBackMessageModel> {

	private PullBackMessageModel model = null;

	private PullBackMessageService service;
	
	@Autowired
	@Qualifier("pullBackMessageService")
	public void setService(PullBackMessageService service) {
		this.service = service;
	}

	public String showPage() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		try {
			this.service.showPage(paramsMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ActionSupport.SUCCESS;
	}
	
	public String showSendPullBackMessagePage() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		this.service.showSendPullBackMessagePage(paramsMap);
		return SUCCESS;
	}
	

	public void queryList() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();
		
		try {
			List list = this.service.getList(start, length, pageResponse, paramsMap);
			pageResponse.setAaData(list);
			pageResponse.setSEcho(pageRequest.getSEcho());
			
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void sendMessage() {
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String operator = getUserVO().getUsername();
		paramsMap.put("operator", operator);
		String message = service.sendMessage(paramsMap);

		JsonObject object = new JsonObject();
		object.addProperty("message", message);
		try {
			sendJsonMessage(object.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public PullBackMessageModel getModel() {
		if (model == null) {
			model = new PullBackMessageModel();
		}
		return model;
	}

}
